package com.mybatis.mp.scenery.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement
public class DataSourceConfig {

    @Autowired
    SceneryDatasourceDto sceneryDatasourceDto;

    @Autowired
    DruidConfig druidConfig;

    @Bean(name = "sceneryDataSource")
    public DataSource sceneryDataSource() {
        return getDataSource(sceneryDatasourceDto.getDriverClassName(), sceneryDatasourceDto.getUrl(), sceneryDatasourceDto.getUsername(), sceneryDatasourceDto.getPassword());
    }

    @Bean(name = "sceneryTransactionManager")
    public DataSourceTransactionManager sceneryTransactionManager() {
        return new DataSourceTransactionManager(sceneryDataSource());
    }

    private DataSource getDataSource(String driverClassName, String url, String username, String password) {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setMaxActive(druidConfig.getMaxActive());
        dataSource.setInitialSize(druidConfig.getInitialSize());
        dataSource.setMaxWait(druidConfig.getMaxWait());
        dataSource.setMinIdle(druidConfig.getMinIdle());
        dataSource.setTimeBetweenEvictionRunsMillis(druidConfig.getTimeBetweenEvictionRunsMillis());
        dataSource.setMinEvictableIdleTimeMillis(druidConfig.getMinEvictableIdleTimeMillis());
        dataSource.setValidationQuery(druidConfig.getValidationQuery());
        dataSource.setTestWhileIdle(druidConfig.getTestWhileIdle());
        dataSource.setTestOnBorrow(druidConfig.getTestOnBorrow());
        dataSource.setTestOnReturn(druidConfig.getTestOnReturn());
        dataSource.setMaxOpenPreparedStatements(druidConfig.getMaxOpenPreparedStatements());
        dataSource.setRemoveAbandoned(druidConfig.getRemoveAbandoned());
        dataSource.setRemoveAbandonedTimeout(druidConfig.getRemoveAbandonedTimeout());
        return dataSource;
    }


}

